package com.hf.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hf.entity.Roles;
import com.hf.entity.RolesParam;
import com.hf.entity.UserRoles;
import com.hf.service.IRolesService;
import com.hf.service.IUserRolesService;
import com.hf.util.Result;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author eight
 * @since 2021-06-06
 */
@RestController
@RequestMapping("/roles")
public class RolesController {
	@Autowired
	IRolesService iRolesService;
	@Autowired
	IUserRolesService iUserRolesService;

	/**
	 * 多条件分页查询 localhost:8080/roles/getList?page=0&limit=20
	 * 
	 * @param u
	 * @return
	 */
	@GetMapping("/getList")
	public Object getList(RolesParam r) {
		IPage<Roles> p = iRolesService.getList(r);

		List<Roles> list = p.getRecords();
		int num = (int) p.getTotal();
		return new Result(0, "查詢成功", list, num);

	}

	/**
	 * 查询所有角色 localhost:8080/roles/getAllList
	 * 
	 * @return
	 */
	@GetMapping("/getAllList")
	public Object getAllList() {
		List<Roles> list = iRolesService.list();
		return new Result(0, "查詢成功", list, list.size());

	}

	/**
	 * 添加 localhost:8080/roles/insert?roleName=文艺委员
	 * 
	 * @param u
	 * @return
	 */
	@PostMapping("/insert")
	public Object insert(Roles r) {
		if (iRolesService.save(r)) {
			return new Result(0, "添加成功");
		}
		return new Result(1, "添加失败");

	}

	/**
	 * 删除 localhost:8080/roles/delete?id=1
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping("/delete")
	public Object delete(Integer id) {

		List<UserRoles> list = iUserRolesService.getListByRoleId(id);
		if (list.size() == 0) {
			if (iRolesService.removeById(id)) {
				return new Result(0, "删除成功");
			}
			return new Result(1, "删除失败");
		} else {
			return new Result(1, "该角色不能删除");
		}

	}

	/**
	 * 修改 localhost:8080/roles/update?roleName=小组长&id=7
	 * 
	 * @param u
	 * @return
	 */
	@PostMapping("/update")
	public Object update(Roles r) {

		if (iRolesService.saveOrUpdate(r)) {
			return new Result(0, "修改成功");
		}
		return new Result(1, "修改失败");
	}
}
